<template>
	<div>
		<header ref="box1" class="flex-between-center margin-bottom-4">
			<el-button size="small" type="default" icon="el-icon-postcard">
				<span>岗位: </span>
				<span style="font-size: 13px;font-weight: 700;">{{ tableData.length }}个</span>
			</el-button>
			<div>
				<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="机台编号或名称" class="search-bar-item-size2 item-gap" @on-enter="onSearchBtn"></jk-search-input>
				<jk-search-input v-model="searchParams.empName" placeholder="人员名称" class="search-bar-item-size3" show-search @on-enter="onSearchBtn"></jk-search-input>
			</div>
		</header>
		<jk-table border :loading="contentLoading" :data="tableData" :height="dialogTableHeight - 50">
			<vxe-column title="岗位" align="center" field="postName" :width="140">
				<template slot="header">
					<div v-if="!readonly" class="flex-center link-style" @click="onAddPostBtn">
						<span class="el-icon-plus item-gap"></span>
						<span style="font-weight: 400;">添加岗位</span>
					</div>
					<div v-else>岗位</div>
				</template>
				<template slot-scope="scope">
					<div class="flex-start-center" style="flex-direction: column;font-size: 14px;">
						<div v-if="scope.row.isAdd">
							<el-select v-model="scope.row.postId" size="mini" placeholder="岗位" @change="onSelectPostChange($event, scope)">
								<el-option
									v-for="item in postList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
									:disabled="tableData.some(x => x.postId === item.id)"
								></el-option>
							</el-select>
						</div>
						<div v-else class="width-100-percent">
							<el-button v-if="!readonly" class="width-100-percent" size="small" @click="onAddEmpBtn(scope.row)">{{ scope.row.postName }}</el-button>
							<el-button v-else class="width-100-percent" size="small">{{ scope.row.postName }}</el-button>
						</div>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="人员及机台明细" align="left" field="empList" :min-width="180">
				<template slot="header">
					<div class="flex-start-center">
						<div class="width-100-percent flex-center">
							<legend-bar></legend-bar>
						</div>
					</div>
				</template>
				<template slot-scope="scope">
					<div class="width-100-percent">
						<jk-button v-if="!scope.row.scheduleEmpList || !scope.row.scheduleEmpList.length" class="el-icon-plus" size="mini" @click="onAddEmpBtn(scope.row)">人员</jk-button>
						<div v-for="(empItem, empIndex) in scope.row.scheduleEmpList" :key="empIndex" class="width-100-percent flex-start-center-wrap">
							<div style="width: 110px;padding: 2px;" class="flex-start-center">
								<el-tag class="flex-between-center width-100-percent">
									<!--<el-tag class="flex-between-center width-100-percent" :closable="!readonly" @close="onDeleteEmpBtn(scope.row, empItem)">-->
									<span class="el-icon-">{{ empItem.empName }}</span>
								</el-tag>
							</div>
							<div style="width: calc(100% - 130px)" class="">
								<div v-for="(dateTimeItem) in empItem.scheduleEmpWorkTimeList || []" :key="dateTimeItem.id" class="flex-start-center">
									<el-tag style="width: 120px;flex-shrink: 0;margin-right: 4px;" :closable="true" type="info" @close="onDeleteEmpBtn(scope.row, empItem, dateTimeItem)">{{ `${transformDateTime(dateTimeItem.startDateTime)}~${transformDateTime(dateTimeItem.endDateTime)}` }}</el-tag>
									<div style="width: calc(100% - 124px)" class="flex-start-center-wrap">
										<div
											v-for="machineItem in dateTimeItem.empMachineList"
											:key="machineItem.machineId"
											style="padding: 2px;width: calc(100% / 6);"
										>
											<el-tag style="cursor: pointer;" type="info" effect="plain" class="width-100-percent flex-between-center" :closable="!readonly" @click="onSetSpinGroupBtn(empItem, scope.row, machineItem)" @close="onDeleteMachineBtn(empItem, machineItem)">
												<div class="flex-start-center">
													<div :style="setBgColor(machineItem)" style="width: 8px;height: 8px;border-radius: 1px;margin-right: 4px;"></div>
													<span>{{ machineItem.machineCode }}</span>
												</div>
											</el-tag>
										</div>
										<div v-if="!readonly" style="padding: 2px;">
											<el-tag type="info" style="margin: 2px;cursor: pointer;" class="el-icon-plus" @click="onAddMachineBtn(scope.row, empItem, dateTimeItem)"></el-tag>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</template>
			</vxe-column>
		</jk-table>
		<checkbox-emp-dialog
			:default-select-rows="schedulePostEmpList"
			check-key-name="empId"
			:dialog-state="checkboxEmpDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxEmpDialog"
			@on-confirm="onConfirmBtnOfCheckboxEmpDialog"
		></checkbox-emp-dialog>
		<checkbox-machine-dialog
			:workshop-id="searchParams.workshopId"
			:schedule-shift-id="searchParams.scheduleShiftId"
			:default-select-rows="selectedMachineList"
			check-key-name="machineId"
			:dialog-state="selectMachineDialogState"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
		></checkbox-machine-dialog>
		<set-spin-group-dialog
			:readonly="readonly"
			:select-machine-item="selectMachineItem"
			:dialog-state="setSpinGroupDialogState"
			@on-visible-change="onVisibleChangeOfSetSpinGroupDialog"
			@on-confirm="onConfirmBtnOfSetSpinGroupDialog"
		></set-spin-group-dialog>
	</div>
</template>

<script>
    import {
        workforceManagementScheduleEmpCreate, workforceManagementScheduleEmpCreateByPost,
        workforceManagementScheduleEmpMachineCreate,
        workforceManagementScheduleEmpMachineDelete, workforceManagementScheduleEmpPostDeleteByPost,
        workforcemanagementScheduleGroupDeleteEmp,
        workforceManagementScheduleGroupPostList,
        workforcemanagementScheduleGroupUpdate
    } from '../../../../../../api/schedule/scheduling';
    import setSpinGroupDialog from '../../set-spin-group-dialog';
    import checkboxMachineDialog from '../../../../empMachine/components/schedule-checkbox-machine-dialog';
    import checkboxEmpDialog from '../../checkbox-emp-dialog';
    import { systemPostPage } from '../../../../../../api/system/post';
    import calHeight from '../../../../../../mixins/cal-dialog-height';
    import { tipsBar } from '../../../../../../utils/jk/jk-tool';
    import legendBar from '../../legend-bar';
    import legendList from '../../legend-bar/lengend-list';
    export default {
        mixins: [calHeight, legendList],
        components: {
            legendBar,
            setSpinGroupDialog,
            checkboxMachineDialog,
            checkboxEmpDialog
        },
        props: {
            readonly: { // 只读
                type: Boolean,
                default: false
            },
            checkData: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        data() {
            return {
                selectMachineItem: {},
                setSpinGroupDialogState: false,
                selectedMachineList: [],
                selectMachineDialogState: false,
                schedulePostEmpList: [],
                contentLoading: false,
                tableData: [],
                postList: [],
                searchParams: {
                    scheduleShiftId: null,
                    scheduleId: this.checkData.scheduleId,
                    scheduleGroupId: this.checkData.scheduleGroupId,
                    empName: '',
                    machineNameOrCode: ''
                },
                checkboxEmpDialogState: false,
                selectedEmpItem: {},
                addEmpInfo: {}
            };
        },
        methods: {
            transformDateTime(e) {
                let str = e && e.split(' ') ? e.split(' ')[1] : '';
                const arr = str.split(':');
                str = arr[0] + ':' + arr[1];
                return str;
            },
            onConfirmBtnOfSetSpinGroupDialog() {
                this.setSpinGroupDialogState = false;
                this.getDependentData();
            },
            onVisibleChangeOfSetSpinGroupDialog(e) {
                this.setSpinGroupDialogState = e;
            },
            onSetSpinGroupBtn(empItem, postItem, machineItem) {
                /* this.selectMachineItem = {
                    empItem,
                    postItem,
                    machineItem
                };
                this.setSpinGroupDialogState = true;*/
            },
            onAddMachineBtn(postItem, empItem, dateTimeItem) {
                this.selectedMachineList = JSON.parse(JSON.stringify(dateTimeItem.empMachineList));
                this.addMachineInfo = {
                    scheduleEmpPostDateId: dateTimeItem.id,
                    postId: postItem.postId,
                    scheduleEmpId: empItem.id
                };
                this.selectMachineDialogState = true;
            },
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            onConfirmBtnOfSelectMachineDialog(arr) {
                const params = {
                    postId: this.addMachineInfo.postId,
                    scheduleEmpId: this.addMachineInfo.scheduleEmpId,
                    scheduleEmpPostDateId: this.addMachineInfo.scheduleEmpPostDateId,
                    machineList: arr.map(x => {
                        return {
                            machineCode: x.code,
                            machineId: x.id,
                            machineName: x.name
                        };
                    })
                };
                workforceManagementScheduleEmpMachineCreate(params).then(res => {
                    this.selectMachineDialogState = false;
                    if (res.data.status === 200) {
                        this.getListRequest();
                    }
                });
            },
            onConfirmBtnOfCheckboxEmpDialog(arr) {
                const empData = {
                    postId: this.addEmpInfo.postId,
                    scheduleGroupId: this.checkData.scheduleGroupId,
                    empIds: arr.map(x => x.id)
                };
                workforceManagementScheduleEmpCreateByPost(empData).then(res => {
                    if (res.data.status === 200) {
                        this.checkboxEmpDialogState = false;
                        this.getDependentData();
                    }
                });
            },
            updateRequest(empList = []) {
                const payload = {};
                payload.scheduleEmpList = empList;
                payload.scheduleId = this.searchParams.scheduleId;
                payload.scheduleGroupId = this.searchParams.scheduleGroupId;
                return workforcemanagementScheduleGroupUpdate(payload);
            },
            onVisibleChangeOfCheckboxEmpDialog(e) {
                this.checkboxEmpDialogState = e;
            },
            onDeleteMachineBtn(empItem, machineItem) {
                this.$msgbox({
                    title: '消息',
                    message: `确定将"${machineItem.machineName}"从"${empItem.empName}"的身上移除吗？`,
                    iconClass: 'el-icon-question',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            workforceManagementScheduleEmpMachineDelete({
                                id: machineItem.id
                            }).then(res => {
                                instance.confirmButtonLoading = false;
                                instance.confirmButtonText = '确定';
                                if (res.data.status === 200) {
                                    done();
                                    this.getListRequest();
                                }
                            });
                        } else {
                            done();
                        }
                    }
                });
            },
            onDeleteEmpBtn(postItem, empItem, dateTimeItem) {
                this.$msgbox({
                    title: '消息',
                    message: `确定移除"${empItem.empName}"在"${postItem.postName}"上的工作时间(${this.transformDateTime(dateTimeItem.startDateTime)}~${this.transformDateTime(dateTimeItem.endDateTime)})吗？`,
                    iconClass: 'el-icon-question',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            workforceManagementScheduleEmpPostDeleteByPost({
                                scheduleEmpId: empItem.id,
                                postId: postItem.postId,
                                scheduleEmpPostDateId: dateTimeItem.id
                            }).then(res => {
                                instance.confirmButtonLoading = false;
                                instance.confirmButtonText = '确定';
                                if (res.data.status === 200) {
                                    done();
                                    this.getListRequest();
                                }
                            });
                        } else {
                            done();
                        }
                    }
                });
            },
            onSelectPostChange(e, scope) {
                const postItem = this.postList.find(x => x.id === e) || {};
                this.$set(this.tableData[scope.rowIndex], 'postCode', postItem.code);
                this.$set(this.tableData[scope.rowIndex], 'postName', postItem.name);
            },
            onAddPostBtn() {
                this.tableData.unshift({
                    postId: null,
                    postCode: '',
                    postName: '',
                    isAdd: true,
                    scheduleEmpList: []
                });
            },
            onAddEmpBtn(row) {
                if (row.postId) {
                    this.schedulePostEmpList = row.scheduleEmpList;
                    this.addEmpInfo = row;
                    this.checkboxEmpDialogState = true;
                } else {
                    tipsBar(this, 'custom', 'warning', '岗位不能为空!');
                }
            },
            getListRequest() {
                if (this.searchParams.scheduleId && this.searchParams.scheduleGroupId) {
                    return workforceManagementScheduleGroupPostList(this.searchParams).then(res => {
                        this.contentLoading = false;
                        if (res.data.status === 200) {
                            this.tableData = res.data.res;
                        }
                    });
                }
            },
            getPostListRequest() {
                return systemPostPage({ auditState: 1, pageSize: 1000 }).then(res => {
                    if (res.data.status === 200) {
                        this.postList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.contentLoading = true;
                await this.getPostListRequest();
                await this.getListRequest();
                this.contentLoading = false;
            },
            onSearchBtn() {
                this.getDependentData();
            }
        },
        mounted() {
            this.searchParams.workshopId = this.checkData.workshopId;
            this.searchParams.scheduleId = this.checkData.scheduleId;
            this.searchParams.scheduleShiftId = this.checkData.shiftItem.id;
            this.searchParams.scheduleGroupId = this.checkData.scheduleGroupId;
            this.getDependentData();
        },
        destroyed() {
            this.$set(this.searchParams, 'scheduleId', null);
            this.$set(this.searchParams, 'scheduleGroupId', null);
        }
    };
</script>
<style scoped lang="scss">
</style>
